/*http请求*/
const rp = require('request-promise');
/*xml*/
const xml2js = require('xml2js');
/*sha1签名*/
const sha1 = require('node-sha1');
/*md5签名*/
const md5 = require('js-md5');
/*工具函数*/
const jason_tools = require('../../../utils/jason_tools');
/*数据库操作*/
const basics_db = require('../../dbhelper/basics_db');

/**
 * 获取access_token
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.getWXAccessToken = async (ctx, next) => {
  /*根参数*/
  let appid = 'wx3d51251099a35021';
  let secret = 'c7dedd3743776dc0f22067ed7f0dcd8d';

  /*参数声明*/
  let body = ctx.request.body;

  /*函数体*/
  let options = {
    uri: 'https://api.weixin.qq.com/cgi-bin/token',
    qs: {
      appid,
      secret,
      grant_type: 'client_credential'
    },
    headers: {
      'User-Agent': 'Request-Promise'
    },
    json: true // Automatically parses the JSON string in the response
  };
  let res;
  await rp(options)
    .then(function (repos) {
      res = repos;
    })
    .catch(function (err) {
      res = err;
    });

  return ctx.body = res;
}

/**
 * 微信用code获取access_token
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.getWXAccessTokenByCode = async (ctx, next) => {
  /*根参数*/
  let appid = 'wx3d51251099a35021';
  let secret = 'c7dedd3743776dc0f22067ed7f0dcd8d';

  /*参数声明*/
  let body = ctx.request.body;
  let code = body.code;

  /*函数体*/
  let options = {
    uri: 'https://api.weixin.qq.com/sns/oauth2/access_token',
    qs: {
      appid,
      secret,
      code,
      grant_type: 'authorization_code'
    },
    headers: {
      'User-Agent': 'Request-Promise'
    },
    json: true // Automatically parses the JSON string in the response
  };
  let res;
  await rp(options)
    .then(function (repos) {
      res = repos;
    })
    .catch(function (err) {
      res = err;
    });

  return ctx.body = res;
}

/**
 * 微信用refresh_token刷新code_access_token
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.updataWXAccessToken = async (ctx, next) => {
  /*根参数*/
  let appid = 'wx3d51251099a35021';

  /*参数声明*/
  let body = ctx.request.body;
  let refresh_token = body.refresh_token;

  /*函数体*/
  let options = {
    uri: 'https://api.weixin.qq.com/sns/oauth2/refresh_token',
    qs: {
      appid,
      refresh_token,
      grant_type: 'refresh_token'
    },
    headers: {
      'User-Agent': 'Request-Promise'
    },
    json: true
  };
  let res;
  await rp(options)
    .then(function (repos) {
      res = repos;
    })
    .catch(function (err) {
      res = err;
    });

  return ctx.body = res;
}

/**
 * 微信用access_token获取jsapi_ticket
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.getWXJsapi_ticket = async (ctx, next) => {
  /*参数声明*/
  let body = ctx.request.body;
  let access_token = body.access_token;
  /*函数体*/
  let options = {
    uri: 'https://api.weixin.qq.com/cgi-bin/ticket/getticket',
    qs: {
      access_token: access_token,
      type: 'jsapi'
    },
    headers: {
      'User-Agent': 'Request-Promise'
    },
    json: true
  };
  let res;
  await rp(options)
    .then(function (repos) {
      res = repos;
    })
    .catch(function (err) {
      res = err;
    });

  return ctx.body = res;
}

/**
 * 初始化微信-签名算法
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.getWXAutograph = async (ctx, next) => {
  /*根参数*/
  let appId = 'wx3d51251099a35021';
  /*参数声明*/
  let body = ctx.request.body;
  let nonceStr = body.nonceStr;
  let jsapi_ticket = body.jsapi_ticket;
  let timestamp = body.timestamp;
  let uri = body.url;

  let signature = 'jsapi_ticket=' + jsapi_ticket + '&noncestr=' + nonceStr + '&timestamp=' + timestamp + '&url=' + uri;
  signature = sha1(signature);

  return ctx.body = {
    appId,
    timestamp,
    nonceStr,
    signature
  };
}

/**
 * 微信商户生成订单
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.unifiedorder = async (ctx, next) => {
  /*根参数*/
  let appid = 'wx3d51251099a35021';
  let mch_id = '1499709282';
  let nonce_str = jason_tools.generateMixed(30);
  let out_trade_no = new Date().getTime();
  /*参数声明*/
  let body = ctx.request.body;
  /*数据操作*/
  let data = await basics_db.findOne('activities', {
    id: parseInt(body.activitiesId)
  });
  if (!data) {
    return ctx.body = "参数错误！";
  }

  let params = {
    appid,
    mch_id,
    nonce_str,
    openid: body.openid,
    body: data.title,
    detail: data.describe,
    attach: data.attach,
    out_trade_no,
    total_fee: data.price,
    spbill_create_ip: ctx.request.ip,
    notify_url: 'https://qingjingzhi.com/activities',
    trade_type: 'JSAPI',
  }
  /*MD5加密*/
  let stringA = jason_tools.removeEmpyParam(params);
  stringA = jason_tools.sortByASCII(stringA);
  let stringSignTemp = stringA + "&key=5dcf6acf62905f70190981eee4e17e94";
  params.sign = md5(stringSignTemp).toUpperCase();
  /*转化成xml格式*/
  var builder = new xml2js.Builder();
  var paramsXML = builder.buildObject(params);

  /*函数体*/
  let options = {
    method: 'POST',
    uri: 'https://api.mch.weixin.qq.com/pay/unifiedorder',
    body: paramsXML,
    headers: {
      'Connection': 'Keep-Alive',
      'Content-Type': 'application/xml;charset=utf-8',
      'Content-length': paramsXML.length
    }
  };
  let res;
  await rp(options)
    .then(function (repos) {
      res = {
        paramsXML: JSON.stringify(paramsXML),
        repos: repos
      };
    })
    .catch(function (err) {
      res = err;
    });

  return ctx.body = res;
}

/**
 * 微信支付
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.payment = async (ctx, next) => {
  /*根参数*/
  let appId = 'wx3d51251099a35021';
  let nonceStr = jason_tools.generateMixed(30);
  let timeStamp = Date.parse(new Date()).toString();
  timeStamp = timeStamp.substr(0, 10);
  /*参数声明*/
  let body = ctx.request.body;
  /*数据操作*/
  let data = await basics_db.findOne('orders', {
    buyerid: body.openid
  });
  if (!data) {
    return ctx.body = "参数错误！";
  }

  let params = {
    appId,
    timeStamp,
    nonceStr,
    package: 'prepay_id=' + data.tradeid,
    signType: 'MD5'
  }
  /*MD5加密*/
  let stringA = jason_tools.sortByASCII(params);
  let stringSignTemp = stringA + "&key=5dcf6acf62905f70190981eee4e17e94";
  params.paySign = md5(stringSignTemp).toUpperCase();

  return ctx.body = params;
}


